package games.gong.durid.config;

/**
 * @ClassName SecurityConfig
 * @PackageName games.gong.durid.config
 * @projectName springboot
 * @Description Spring Security 配置类，用于配置认证、授权、密码加密以及JWT过滤器等安全相关组件。
 * @Author games
 * @Date 2025/8/19 下午4:26
 * @Version 1.0
 */


import games.gong.durid.security.JwtAuthFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    private final JwtAuthFilter jwtAuthFilter;

    /**
     * 构造函数注入 JwtAuthFilter 实例
     *
     * @param jwtAuthFilter JWT 认证过滤器实例
     */
    public SecurityConfig(JwtAuthFilter jwtAuthFilter) {
        this.jwtAuthFilter = jwtAuthFilter;
    }

    /**
     * 配置安全过滤器链，定义请求的权限控制策略和安全机制
     *
     * @param http HttpSecurity 对象，用于构建安全配置
     * @return SecurityFilterChain 安全过滤器链对象
     * @throws Exception 配置过程中可能抛出异常
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                // 禁用 CSRF 保护（适用于无状态 API）
                .csrf(csrf -> csrf.disable())
                // 设置会话管理策略为无状态，不创建会话
                .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        // ✅ 放行接口：登录、注册、Swagger 文档、Druid 监控等无需认证即可访问的路径
                        .requestMatchers(
                                "/api/users/login",
                                "/api/users/register",
                                "/swagger-ui.html",
                                "/swagger-ui/**",
                                "/v3/api-docs/**",
                                "/v3/api-docs",
                                "/swagger-resources/**",
                                "/webjars/**",
                                "/druid/**"
                        ).permitAll()
                        // 其他所有请求都需要身份认证
                        .anyRequest().authenticated()
                )
                // 在 UsernamePasswordAuthenticationFilter 前添加 JWT 认证过滤器
                .addFilterBefore(jwtAuthFilter, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    /**
     * 配置密码编码器，使用 BCrypt 加密算法
     *
     * @return PasswordEncoder 密码编码器实例
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置认证管理器，用于处理用户认证逻辑
     *
     * @param config AuthenticationConfiguration 配置对象
     * @return AuthenticationManager 认证管理器实例
     * @throws Exception 获取认证管理器时可能抛出异常
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
}